package org.apache.ibatis.common.type;

import java.security.interfaces.ECKey;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Name EnumTypeHandler
 * @Description: [SQL String -> JAVA Enum] 类型处理器
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-05-10 17:49:17
 **/
public class EnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
    private final Class<E> type;

    public EnumTypeHandler(Class<E> type) {
        if (type == null) throw new IllegalArgumentException("Type 类型参数不能为 null。");
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) ps.setString(i, parameter.name());
        else ps.setObject(i, parameter.name(), jdbcType.TYPE_CODE);
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return result == null ? null : Enum.valueOf(type, result);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return result == null ? null : Enum.valueOf(type, result);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return result == null ? null : Enum.valueOf(type, result);
    }
}

